package com.green.cosme.servlet;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.green.cosme.batch.scraper.Item;
import com.green.cosme.batch.scraper.KenkoComScraper;
import com.green.cosme.util.PMF;

/**
 * Register ServletClass
 * 
 * @author M.T.
 * 
 */
@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		KenkoComScraper scraper = new KenkoComScraper();
		List<Item> items = null;
		try {
			items = scraper.exec();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			List<Item> oldItems = (List<Item>) pm.newQuery(Item.class).execute();
			pm.deletePersistentAll(oldItems);
			pm.makePersistentAll(items);
		} finally {
			pm.close();
		}
		resp.sendRedirect("complete.html");
	}
}
